<?php

namespace app\common\model;

use think\Model;
use app\common\model\Config;

class ShareStrategy extends Model
{
    // 表名
    protected $name = 'share_strategy';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    //关联策略交易表
    public function strategyTransaction()
    {
        return $this->hasMany('StrategyTransaction','strategy_id','id');
    }

    /**
     * 创建新策略持仓
     * @param user_id
     * @param all_no
     * @param name
     * @param price
     * @param num
     * @param isAuto
     */
    public function newStrategy(array $params)
    {
        // 会员信息
        $userInfo = User::get($params['user_id']);
        \think\Log::record('11111');
        //获取金额信息
        $conList = Config::getVal(['min_buy_num','management_expense','add_warehouse']);
        //保证金
        $earnestMoney = $params['price'] * $params['num'] / 10;
        //管理费
        if( $params['is_auto'] == 1 ){
            $managementExpense = $earnestMoney * $conList['management_expense'] * 0.01 * 10;
        }else{
            $managementExpense = 0;
        }
        \think\Log::record('222222');
        //建仓费
        $addWarehouse = $earnestMoney * 10 * $conList['add_warehouse'];

        if( ($earnestMoney + $managementExpense + $addWarehouse) > $userInfo->money ){
            $this->error = '余额不足';
            return false;
        }
        \think\Log::record('33333');
        \think\Log::record(json_encode($params));
        //组装数据
        $params['total_lever_num']  = $params['num'];
        $params['total_earnest']    = $params['price'] * $params['num'] / 10;
        $params['is_ent'] = 1;
        \think\Log::record('4444');
        \think\Log::record(json_encode($params));
        //创建新策略
        if( $this->allowField(true)->save($params) == false ){
            $this->error = '创建新策略失败';
            return false;
        }
        \think\Log::record('5555');
        //新增交易记录
        $strategyTransaction = new StrategyTransaction();

        $strategyTransaction->user_id       = $userInfo->id;
        $strategyTransaction->strategy_id   = $this->id;
        $strategyTransaction->buy_price     = $params['price'];
        $strategyTransaction->lever_num     = $params['num'];
        $strategyTransaction->type          = 'new';
        $strategyTransaction->name          = $params['name'];
        $strategyTransaction->no            = $params['all_no'];
        $strategyTransaction->buy_time      = time();
        $strategyTransaction->earnest       = $params['price'] * $params['num'] / 10;
        if( $strategyTransaction->save() == false ){
            $this->error = '创建新交易失败';
            return false;
        }

        //扣除余额
        updateMoney($userInfo,-$earnestMoney,'保证金');
        //建仓费
        if( $addWarehouse > 0 ){
            updateMoney($userInfo,-$addWarehouse,'建仓费');
        }
        if( $managementExpense > 0 ){
            updateMoney($userInfo,-$managementExpense,'管理费');
        }
        return true;
    }

    /**
     * 补仓
     * @param user_id
     * @param all_no
     * @param deal_price
     * @param num
     * @param isAuto
     */
    public function appendStrategy(array $params)
    {
        // 会员信息
        $userInfo = User::get($params['user_id']);

        //获取金额信息
        $conList = Config::getVal(['min_buy_num','management_expense','add_warehouse']);
        //保证金
        $earnestMoney = $params['price'] * $params['num'] / 10;
        //管理费
        $managementExpense = $params['is_auto'] == 1 ? $earnestMoney * $conList['management_expense'] * 0.01 * 10 : 0;
        //建仓费
        $addWarehouse = $earnestMoney * 10 * $conList['add_warehouse'];
        if( ($earnestMoney + $managementExpense + $addWarehouse) > $userInfo->money ){
            $this->error = '余额不足';
            return false;
        }

        //修改策略数据
        $this->total_lever_num += $params['num'];
        $this->total_earnest += $params['num'] * $params['price'] / 10;
        $this->updatetime = time();
        if( $this->save() == false ){
            $this->error = '修改策略数据失败';
            return false;
        }

        //创建策略交易记录
        $strategyTransaction                = new StrategyTransaction();
        $strategyTransaction->user_id       = $userInfo->id;
        $strategyTransaction->strategy_id   = $this->id;
        $strategyTransaction->buy_price     = $params['price'];
        $strategyTransaction->lever_num     = $params['num'];
        $strategyTransaction->name          = $params['name'];
        $strategyTransaction->no            = $params['all_no'];
        $strategyTransaction->buy_time      = time();
        $strategyTransaction->earnest       = $params['price'] * $params['num'] / 10;
        if($strategyTransaction->save() == false){
            $this->error = '创建策略交易记录失败';
            return false;
            
        }

        //扣除余额
        updateMoney($userInfo,$earnestMoney * -1,'保证金');
        if( $addWarehouse > 0 ){
            updateMoney($userInfo,$addWarehouse * -1,'建仓费');
            //交易佣金
            updateMoney($userInfo,$params['price'] * $params['num'] * $conList['commission'] * 0.01 *-1,'交易佣金');
        }
        if( $managementExpense > 0 ){
            updateMoney($userInfo,$managementExpense * -1,'管理费');
        }

        return true;
    }

    /**
     * 平仓
     * @param price
     * @param num
     */
    public function pay(array $params)
    {
        // 会员信息
        $userInfo = User::get($this->user_id);

        if($this->can_use_num < $params['num']){
            $this->error = '当前可交易数量不足';
            return false;
        }
        //获取金额信息
        $conList = Config::getVal(['commission','stamp_duty','transfer_fee']);

        if( bcsub($this->total_lever_num,$params['num']) <= 0 ){
            $this->status = 0;
            $params['num'] = $this->total_lever_num;
        }

        //策略表里总保证金要扣除的保证金
        $earnest = bcmul(
            bcdiv($this->total_earnest,$this->total_lever_num),
            $params['num'],
            2
        );
        $this->total_lever_num = bcsub($this->total_lever_num,$params['num']);
        $this->total_earnest = bcsub($this->total_earnest,$earnest);
        $this->can_use_num = bcsub($this->can_use_num,$params['num']);
        $this->save();

        //持有股票的保证金平仓后要退回到可用资金
        updateMoney($userInfo,$earnest,'委托平仓保证金');

        //创建策略交易记录
        $transaction = [];
        $strategyTransaction = new StrategyTransaction();

        $buy_price = bcmul(
            bcdiv($this->total_earnest,$this->total_lever_num),
            10,
            2
        );

        $transaction['user_id']       = $userInfo->id;
        $transaction['strategy_id']   = $this->id;
        $transaction['type']          = 'reduce';
        $transaction['buy_price']     = $buy_price;
        $transaction['pay_price']     = $params['price'];
        $transaction['lever_num']     = $params['num'];
        $transaction['name']          = $this->name;
        $transaction['no']            = $this->all_no;
        //保证金记录
        $transaction['earnest']       = $earnest;
        $transaction['pay_time']      = time();
        $transaction['buy_time']      = $this->createtime;
        $transaction['createtime']    = time();
        $transaction['updatetime']    = time();
        $strategyTransaction->insert($transaction);

        //每股盈亏
        $profit = bcsub(
            $params['price'],
            bcdiv($this->total_earnest,$this->total_lever_num,2) * 10,
            2
        );
        //平仓后的钱
        updateMoney($userInfo,bcmul($profit,$params['num'],2),'盈亏');
        //交易佣金
        updateMoney($userInfo,floatval($params['price']) * intval($params['num']) * floatval($conList['commission']) * -1,'交易佣金');
        //印花税
        updateMoney($userInfo,floatval($params['price']) * intval($params['num']) * floatval($conList['stamp_duty']) * -1,'印花税');
        //过户费
        updateMoney($userInfo,floatval($params['price']) * intval($params['num']) * floatval($conList['transfer_fee']) * -1,'过户费');
        //记录累计盈亏
        updateCumulative($userInfo,$profit * intval($params['num']),'累计盈亏');

        return true;
    }

}
